import { memo, useEffect } from 'react'
import { Occupy, setRule } from '../services'
import { DatePicker, Form, Input, InputNumber, Modal } from 'antd'
import { parseOccupyFee, stringifyOccupyFee } from '@/utils/common'
import dayjs from 'dayjs'
import { useRequest } from 'ahooks'
import OccupyFee from './OccupyFee'
import getUUID from '@/utils/getUUID'

export interface SetRuleModalProps {
  rule?: Occupy
  onCancel?: (refresh: boolean) => void
}

const SetRuleModal: React.FC<SetRuleModalProps> = props => {
  const [form] = Form.useForm()
  const { runAsync, loading } = useRequest(setRule, {manual: true})

  const onCancel = (refresh: boolean) => {
    form.resetFields()
    props.onCancel?.(refresh)
  }

  const onOk = () => {
    form.validateFields()
    .then((values: any) => {
      if (values.feeList.at(-1).endTime !== 1439) {
        Modal.warn({
          title: '提示',
          content: '占用价格尚有剩余时间未分配',
        })
        return Promise.reject()
      }
      return runAsync({
        stationId: values.stationId,
        feeInfo: stringifyOccupyFee(values.feeList),
        freeTime: values.freeTime,
        maxMoney: values.maxMoney,
        beginDay: values.timeRange[0].format('YYYY-MM-DD'),
        endDay: values.timeRange[1].format('YYYY-MM-DD'),
      })
    })
    .then(() => {
      onCancel(true)
    })
  }

  useEffect(() => {
    if (props.rule) {
      const { stationId, stationName, freeTime, feeInfo, maxMoney, beginDay, endDay } = props.rule
      const feeList = parseOccupyFee(feeInfo)
      form.setFieldsValue({
        stationId,
        stationName,
        freeTime: freeTime || 10,
        feeList: feeList.length ? feeList : [{
          fakeId: getUUID(),
          startTime: 0,
          endTime: 1439,
          price: 0,
        }],
        maxMoney,
        timeRange: beginDay ? [dayjs(beginDay), dayjs(endDay)] : undefined,
      })
    }
  }, [props.rule])

  return (
    <Modal
      title='占用价格配置'
      open={!!props.rule}
      onCancel={() => onCancel(false)}
      onOk={onOk}
      confirmLoading={loading}
      destroyOnClose
      width={800}
    >
      <Form form={form} name='setRuleForm'>
        <Form.Item name='stationId' noStyle><Input hidden /></Form.Item>
        <Form.Item label='电站名称' name='stationName' required>
          <Input disabled />
        </Form.Item>
        <Form.Item label='免费时长' required>
          <Form.Item name='freeTime' rules={[{required: true, message: '请输入免费时长'}]} noStyle>
            <InputNumber min={10} precision={0} style={{width: 240}} placeholder='请输入' addonAfter='分钟' />
          </Form.Item>
          <div>免费时长内不收费，免费时长不得低于<span style={{color: 'var(--ant-color-primary)'}}>10分钟</span>。</div>
        </Form.Item>
        <Form.Item label='占用价格' name='feeList' rules={[{required: true, message: '请设置计费区间'}]}>
          <OccupyFee />
        </Form.Item>
        <Form.Item label='最大收费' required>
          <Form.Item name='maxMoney' rules={[{required: true, message: '请输入免费时长'}]} noStyle>
            <InputNumber min={0} max={500} precision={2} style={{width: 240}} placeholder='请输入' addonAfter='元' />
          </Form.Item>
          <div>达到此收费金额后，后续占用时长内不再产生额外的花费（不再限制是否首次），收费上限不得高于<span style={{color: 'var(--ant-color-primary)'}}>500 元</span>。</div>
        </Form.Item>
        <Form.Item label='生效时间' name='timeRange' rules={[{required: true, message: '请选择生效时间'}]}>
          <DatePicker.RangePicker placeholder={['请选择', '请选择']} />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default memo(SetRuleModal)
